<template>
    <div class="file-load mouse-active" @click.stop="getFile" :disabled="true">
        <div class="upload-btn" v-if="!fileUrl && !disabled"></div>
        <p class="placeholder" v-if="!fileUrl" v-html="placeholder"></p>
        <el-image v-if="fileUrl && types === 'image' && !URLtype(fileUrl)" :src="fileUrl" style="width:100%; height: 100%;"
            fit="contain"></el-image>
        <video v-if="fileUrl && types === 'video'" :src="fileUrl" controls></video>
        <embed class="my-embed" v-if="fileUrl && types === 'image' && URLtype(fileUrl)" :src="fileUrl"
            type="application/pdf">
        <input type="file" ref="file" style="display: none;" @change="handleFileUpload($event)" :accept="accept">
        <div class="del" @click.stop="del" v-if="fileUrl && !disabled"></div>
        <div class="bg" v-show="loading">
            <div class="my-progress">
                <p>Loading...{{ percentage }} %</p>
                <el-progress type="line" :percentage="percentage" class="progress" :show-text="false"
                    :stroke-width="3"></el-progress>
            </div>
        </div>
</div>
</template>

<script>
import Confirm from '@/components/message/confirm.js';
import axios from 'axios';
import { OSSPolicy } from "@/request/api"
export default {
    props: {
        placeholder: {
            type: String,
            default: "请上传文件"
        },
        accept: {
            type: String,
            default: ""
        },
        size: {
            type: [String, Number],
            default: ''
        },
        types: {
            type: String,
            default: 'image'
        },
        history: {
            type: String,
            default: ''
        },
        disabled: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            fileUrl: this.history,
            loading: false,
            percentage: 0
        }
    },
    methods: {
        del() {
            if (this.$i18n.locale === 'zh') {
                Confirm({ title: '删除项目', message: '确定要删除该附件吗？', left: '取消', right: '删除' })
                    .then(() => {
                        this.$refs.file.value = "";
                        this.fileUrl = "";
                    })
                    .then((ret) => {

                    })
                    .catch((err) => {
                        // 点击取消按钮触发
                        if (err === 'cancel') return
                    })
            } else {
                Confirm({ title: 'Delete Item', message: 'Are you sure you want to delete this attachment?', left: 'Cancel', right: 'Delete' })
                    .then(() => {
                        this.$refs.file.value = "";
                        this.fileUrl = "";
                    })
                    .then((ret) => {

                    })
                    .catch((err) => {
                        // 点击取消按钮触发
                        if (err === 'cancel') return
                    })
            }

        },
        // 打开文件
        getFile() {
            if (this.disabled == true) {
                return;
            } else if (!this.fileUrl) {
                this.$refs.file.click()
            }

        },
        // 获取文件
        handleFileUpload(event) {
            // 阻止发生默认行为
            event.preventDefault();
            let file = this.$refs.file.files[0]
            if (!file) {
                return
            }
            console.log(file);
            if (this.getCode(file) === -1) {
                this.$toast('文件类型不正确', 2000, 'warning');
                this.$refs.file.value = "";
                return;
            } else if (this.getCode(file) === -2) {
                this.$toast('文件体积过大', 2000, 'warning');
                this.$refs.file.value = "";
                return;
            } else {
                this.fileUrl = URL.createObjectURL(file)
                this.getImageSize(this.fileUrl).then(sizeInfo => {
                    const { width, height } = sizeInfo
                })
                this.onUpload(file)
            }

        },
        // 上传文件
        async onUpload(file) {
            let res = await OSSPolicy();
            this.percentage = 0;
            this.loading = true;
            let keys = res.data.data.dir + '/' + this.getUUID() + `_${file.name}`;
            axios({
                url: res.data.data.host,
                headers: {
                    'content-type': 'multipart/form-data'
                },
                method: "post",
                data: {
                    key: keys,
                    policy: res.data.data.policy,
                    signature: res.data.data.signature,
                    ossaccessKeyId: res.data.data.accessKeyId,
                    dir: res.data.data.dir,
                    file: file,
                    host: res.data.data.host,
                    callback: res.data.data.callback,
                    success_action_status: "200"
                },
                onUploadProgress: progressEvent => {
                    //progressEvent.loaded:已上传文件大小
                    //progressEvent.total:被上传文件的总大小
                    let complete = parseInt((progressEvent.loaded / progressEvent.total).toFixed(2) * 100);
                    this.percentage = complete;
                },
            }).then(res1 => {
                console.log(res1);
                this.loading = false;
                if (res1.status == "200") {
                    this.$emit('message', res.data.data.host + '/' + keys)
                    this.fileUrl = res.data.data.host + '/' + keys
                }
            }).catch(err1 => {
                this.$refs.file.value = "";
                this.fileUrl = "";
                this.$toast('上传失败', 2000, 'error');
                this.loading = false;
                console.log(err1);
            })
        },
        getUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
                return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
            })
        },
        // 判断文件类型和大小
        getCode(file) {
            if (this.accept) {
                let type = false;
                let str = this.accept.split(".").join("")
                str.split(',').forEach(item => {
                    if (item === file.name.split('.')[file.name.split('.').length - 1]) {
                        type = true
                    }
                })
                if (type === false) {
                    return -1
                }

            }
            if (this.size && (this.size * 1024 * 1024) < file.size) {
                return -2
            }
        },
        getImageSize(url) {
            return new Promise((resolve) => {
                const img = new Image()
                img.src = url
                if (img.complete) {
                    // 如果图片被缓存，则直接返回缓存数据
                    resolve({ width: img.width, height: img.height })
                } else {
                    img.onload = () => {
                        resolve({ width: img.width, height: img.height })
                    }
                }
            })
        }

    },
    watch: {
        history: {
            deep: true,
            handler(newVal, oldVal) {
                this.fileUrl = newVal;
                this.$emit('message', newVal)
            },
            immediate: true
        },
        fileUrl: {
            deep: true,
            handler(newVal, oldVal) {
                this.$emit('message', newVal)
            },
            immediate: true
        }
    },
    computed: {
        URLtype: function () {
            return function (v) {
                let num = "";
                num = v.split('.');
                num = num[num.length - 1]
                if (num == 'pdf') {
                    return true;
                } else {
                    return false
                }
            }
        }
    }
}
</script>

<style lang="less" scoped>
.my-progress {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    p {
        text-align: center;
    }

    .progress {
        width: 80%;
    }
}

.file-load {
    width: 100%;
    height: 100%;
    background: linear-gradient(315deg, rgba(250, 251, 255, 0.25) 0%, rgba(252, 248, 255, 0.25) 100%);
    border: 0.03rem solid #C5C5CA;
    backdrop-filter: blur(10px);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;

    .upload-btn {
        width: 0.64rem;
        height: 0.64rem;
        background: url('@/assets/img/application/upload.png') no-repeat;
        background-size: cover;
        margin-bottom: 0.21rem;
    }

    .placeholder {
        text-align: center;
        width: 100%;
        font-size: 0.53rem;
        font-family: 'IdeaFonts-DianHei-DEJ', 'IdeaFonts-DianHei';
        font-weight: normal;
        color: #C5C5CA;
        line-height: 0.85rem;
    }

    .del {
        width: 1.28rem;
        height: 1.28rem;
        background: url("@/assets/img/application/del.png") no-repeat;
        background-size: 0.64rem 0.64rem;
        background-position: 50% 50%;
        position: absolute;
        top: 0.21rem;
        right: 0.21rem;
    }

    video {
        object-fit: fill;
        width: 100%;
        height: 100%;
    }

    .bg {
        z-index: 999;
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        background-color: rgba(197, 197, 202, 0.7);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.6rem;
    }
}

.my-embed {
    width: 100%;
    height: 100%;
    object-fit: fill;
}
</style>

